package com.foss.plugin;
import android.app.Activity;
import com.foss.AppLog;
import com.foss.mdm.MdmCmdExecutor;
import com.foss.mdm.ModelMdmCmd;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONException;
/**
 * @author: wzq
 * @date: 14-7-31
 * description: 类说明
 */
public class PluginMdm extends CordovaPlugin {
    private static final String ACTION_CHECK = "check_active";
    private static final String ACTION_ACTIVE = "active";
    private static final String ACTION_COMMAND = "command";


    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        // TODO
        AppLog.i("PluginMdm initialize");

        if(!MdmCmdExecutor.getInstance().isActive()) {
            MdmCmdExecutor.getInstance().active((Activity) webView.getContext());
        }
    }

    @Override
    public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException {
        AppLog.d("plugin Mdm, action=" + action + ",rawArgs=" + rawArgs);
        if(ACTION_CHECK.equals(action)) {
            if(MdmCmdExecutor.getInstance().isActive()) {
                callbackContext.success("true");
            } else {
                callbackContext.success("false");
            }
            return true;
        }

        //
        if(ACTION_ACTIVE.equals(action)) {
            if(!MdmCmdExecutor.getInstance().isActive()) {
                MdmCmdExecutor.getInstance().active((Activity) webView.getContext());
                callbackContext.success();
            }
            return true;
        }

        // 执行指令
        if(ACTION_COMMAND.endsWith(action)) {
            ModelMdmCmd cmd = ModelMdmCmd.getMdmCommand(rawArgs);
            if(cmd == null) {
                callbackContext.error("参数不正确");
            } else {
                boolean cmdResult = false;
                try {
                    cmdResult = MdmCmdExecutor.getInstance().exec(cmd);
                } catch(Exception e) {
                    e.printStackTrace();//无须处理
                }
                if(cmdResult) {
                    callbackContext.success();
                } else {
                    callbackContext.error("执行 mdm 失败");
                }
            }
            return true;
        }

        AppLog.e("未定义的action = " + action);
        return false;
    }
}
